package com.test.study.jdbc;

/**
 * JDBC 的事物管理
 * @author huyong
 *
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Logger;

import org.junit.Test;

public class JDBCTransaction {

	private static final Logger log = Logger.getLogger(JDBCTransaction.class.getCanonicalName());

	@Test
	public void testTransaction() throws SQLException {
		Connection connection = null;
		PreparedStatement pst = null;
		try {
			connection = JdbcUtils.getConnection();
			connection.setAutoCommit(false);
			String sql = "update account set balance=balance+? where name=?";
			pst = connection.prepareStatement(sql);
			pst.setDouble(1, -1000);
			pst.setString(2, "hanmei");
			int executeUpdate = pst.executeUpdate();
			log.info("executeUpdate -  count==> " + executeUpdate);
			pst.setDouble(1, 1000);
			pst.setString(2, "lilei");
			executeUpdate = pst.executeUpdate();
			log.info("executeUpdate +  count==> " + executeUpdate);
			connection.commit();
		} catch (Exception e) {
			log.info(e.getMessage());
			connection.rollback();
		} finally {
			JdbcUtils.close(connection, pst);
		}

	}

}
